import fs from 'fs'
import { fileURLToPath } from 'url'

export const queryCtrlJs = () => {
    let ctrlPath = new URL('../controller', import.meta.url).href
    let ctrlPath2 = fileURLToPath(ctrlPath)
    let ctrlArr = fs.readdirSync(ctrlPath2)
    const ctrlArrJs = ctrlArr.filter(item => item.endsWith("Controller.js")).map(file => `${ctrlPath}/${file}`)

    return ctrlArrJs
}

export const registryRouter = (router, ctrlJs) => {
    ctrlJs.forEach(async item => {
        const { users } = await import(item)
        users.forEach(user => {
            let reqMethod = user.method;
            let reqPath = user.path;
            let reqFn = user.fn;

            if (reqMethod === "get") {
                router.get(reqPath, reqFn)
            }
            if (reqMethod === "post") {
                router.post(reqPath, reqFn)
            }
            if (reqMethod === "delete") {
                router.delete(reqPath, reqFn)
            }
            if (reqMethod === "put") {
                router.put(reqPath, reqFn)
            }
        });
    });
}